import SlimSelect from 'slim-select'


document.addEventListener('DOMContentLoaded', () => {
    initSelect();
    initExcel();

    function initExcel() {
        const excelButton = document.querySelector('#export_button');

        const filteredParams = getUrlParams()
        const buildedFilter = buildFilter(filteredParams);
        const filter = setFilter(buildedFilter);


        excelButton?.addEventListener('click', async event => {


            console.log(event.currentTarget.dataset.url);

            const response = await fetch(`${event.currentTarget.dataset.url}`, {
                method: 'post',
                body: filter,
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                }
            })
            const fileName = await response.text();

            let link = document.createElement('a');
            link.href = fileName;
            link.className = 'req';
            link.download;
            link.click();

        })


    }

    function getUrlParams() {

        const url = new URL(window.location.href);

        const searchParams = url.searchParams;

        let params = Array.from(searchParams)


        const filteredParams = [];
        params.forEach(param => {
            const regex = /filters\[(\S*)\]./gm;
            const key = regex.exec(param[0]);
            if (key != null) {
                filteredParams.push({
                    name: key[1],
                    value: param[1]
                })
            }

        })

        return filteredParams;

    }

    function initSelect() {
        const selects = document.querySelectorAll('select');

        selects.forEach(item => {
            new SlimSelect({
                select: item,
                settings: {
                    placeholderText: 'Выберите'
                }
            })
        });
    }


    function buildFilter(arr) {

        const result = arr.reduce((acc, {name, value}) => {
            acc[name] ??= {name: name, value: []};
            if (Array.isArray(value))
                acc[name].value = acc[name].value.concat(value);
            else
                acc[name].value.push(value);

            return acc;
        }, {});

        return Object.values(result);
    }


    function setFilter(data) {

        const formData = new FormData();
        formData.append('filters', [])

        data.forEach(datum => {
            let filterValue = datum.value;
            const filterName = datum.name;

            filterValue.forEach(value => {
                formData.append(`filters[${filterName}][]`, value);
            })


        })


        return formData;

    }
})

